﻿#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void copyString(char* dst, const char* source)
{
	int len = strlen(source);
	printf("7.输出源字符串source的实际长度，不包括\ 0，即len为：%d\n", len); //12
	for (int i = 0; i < len; ++i)
	{
		dst[i] = source[i];
	}
	//6.在buf末尾，添加\0;
	dst[len] = '\0';
}
void copyStringPointer(char* dst, const char* source)
{
	while (*source != '\0')
	{
		*dst = *source;
		++dst;
		++source;
	}
	*dst = '\0';
}
void copyStringPointerSmart(char* dst, const char* source)
{
	while (*dst++ = *source++);
}
void testStringCopy()
{
	char* source = "hello world!";
	//char buf[1024] = { 0 };
	//5.未初始化字符串buf时，拷贝会出现乱码；因为strlen求的是字符串的有效长度，不包括\0；
	char buf[1024];
	copyString(buf, source);
	printf("4.将字符串常量source拷贝到buf中，则buf为：%s\n", buf);//hello world!-->hello world!烫烫烫烫...

	char* sourceStr = "noting...";
	copyStringPointer(buf, sourceStr);
	printf("8.使用指针来拷贝字符串，则buf为：%s\n", buf);//noting...

	char* sourceStrPointer = "i am so tired!";
	copyStringPointerSmart(buf, sourceStrPointer);
	printf("9.直接用while循环，一步完成指针拷贝字符串，则buf为：%s\n", buf);//i am so tired!
}

void reverseString(char* str)
{
	if (NULL == str)
	{
		return;
	}
	int len = strlen(str);

#if 0
	int start = 0;
	int end = len - 1;
	while (start < end)
	{
		char temp = str[start];
		str[start] = str[end];
		str[end] = temp;

		++start;
		--end;
	}
#else
	//13.使用指针重写上面的步骤；
	char* pStart = str;
	char* pEnd = str + len - 1;
	while (pStart < pEnd)
	{
		char temp = *pStart;
		*pStart = *pEnd;
		*pEnd = temp;

		++pStart;
		--pEnd;
	}

#endif

}
void testStringReverse()
{
	char p[] = "abcde";
	reverseString(p);
	printf("12.将字符串p反转后的结果为：%s\n", p);//edcba --> edcba
}

//main191：字符串操作
int main191()
{
	char str[] = { 'h','e','l','l','o' };
	printf("1.输出字符数组str：%s\n", str);//hello烫烫烫蘿颥4
	//3.strNum[10]中空的内容，默认都为0，即不会出现乱码；
	char strNum[10] = { 'h','e','l','l','o' };
	printf("2.输出10个元素的字符数组strNum：%s\n", strNum);//hello

	//10.字符串拷贝；
	testStringCopy();

	//11.字符串反转；
	testStringReverse();

	system("pause");
	return EXIT_SUCCESS;
}